﻿using System;

namespace Algoritmia.Problems.Fibonacci
{
    public class MemoizedFibonacciNumbers : IFibonacciNumbers
    {
        #region Implementation of IFibonacciNumbers

        public int Number(int n)
        {
            var mem = new int?[n+1];
            Action<int> recursiveFibonacci = null;
            recursiveFibonacci = i =>
                                     {
                                         if (!mem[i].HasValue)
                                         {
                                             if (i <= 1)
                                             {
                                                 mem[i] = i;
                                             }
                                             else
                                             {
                                                 recursiveFibonacci(i - 1);
                                                 recursiveFibonacci(i - 2);
                                                 mem[i] = mem[i - 1] + mem[i - 2];
                                             }
                                         }
                                     };
            recursiveFibonacci(n);
            return mem[n].Value;
        }

        #endregion
    }
}
